var commitOrderStatus = 1;

var check = function () {
    var num = /\d{0,10}/;
    var buyNum = $("#buyNum").val()
    if (!num.test(buyNum)) {
        easyAlert("购买数量请输入正整数");
        return false;
    }
    if (buyNum == null || buyNum == '') {
        easyAlert("请输入购买数量")
        return false;
    }
    var overPlus = parseInt($("#overPlus").val())
    if (parseInt(buyNum) > overPlus) {
        easyAlert("购买数量不能大于库存数量！")
        return false;
    }
    return true;
}
$(function () {
    $("#buyNum").bind("input propertychange", function () {
        if (!check()) {
            return;
        }
        var buyNum = parseInt($("#buyNum").val());
        var price = parseFloat($("#priceHidden").val());
        var sum = buyNum * price;
        if (sum == NaN) {
            $("#sum").text("¥0");
        } else {
            $("#sum").text("¥" + sum);
        }

    });
    $('#commitOrder').click(function () {
        if (commitOrderStatus == 1 && check())
            commitOrder();
    });
    loadBuyerInfo();
    predictSendTime();
});
var payType = 1;
//设计送货的年月份和时间
function predictSendTime() {
    var now = new Date();
    now.setDate(now.getDate() + 3)
    var yr = now.getFullYear();
    var mName = now.getMonth() + 1;
    var dName = now.getDay() + 1;
    var dayNr = ((now.getDate() < 10) ? "0" : "") + now.getDate();
    if (mName == 1) Month = "1";
    if (mName == 2) Month = "2";
    if (mName == 3) Month = "3";
    if (mName == 4) Month = "4";
    if (mName == 5) Month = "5";
    if (mName == 6) Month = "6";
    if (mName == 7) Month = "7";
    if (mName == 8) Month = "8";
    if (mName == 9) Month = "9";
    if (mName == 10) Month = "10";
    if (mName == 11) Month = "11";
    if (mName == 12) Month = "12";
    var DayDateTime = (yr + "-" + Month + "-" + dayNr/*+ " "
     + hours+ minutes+ seconds+ " "+ ampm+" " + hours+ minutes*/
    );
    document.getElementById("rightT").innerText = DayDateTime;
    timerID = setTimeout("predictSendTime()", 1000);
    $("#preRecvTime").val(DayDateTime);
}
//商品信息
var getProduct = function () {
    var b = true;
    var proObjs = $.parseJSON(localStorage.getItem('products'));
    console.log(proObjs);
    if (proObjs != null) {
        var s = '';
        for (var i = 0; i < proObjs.length; i++) {
            s += '<img src="' + proObjs[i].picturePath1 + '" alt="" class="">\
			<div class="">\
			<div class="con_tit">\
			<p>' + proObjs[i].productName + '</p>\
			<span>¥' + proObjs[i].price + '/头</span>\
			<input type="hidden" id="priceHidden" value="' + proObjs[i].price + '"/> \
			</div>\
			<p class="con_normal">类别：' + proObjs[i].specName + '</p>\
			<p class="con_normal">货源地：' + proObjs[i].areaName + '</p>\
			</div>';
            $("#overPlusNum").text("库存" + proObjs[i].overPlusNum + "头");
            $("#overPlus").val(proObjs[i].overPlusNum);
        }
        $('#product').html(s);
    }
}
//下单
var commitOrder = function () {
    if ($('#consAddr').text() == '') {
        easyAlert(contants.buyerNoAddr);
        return;
    }
    var sumPrice = 0;
    $('.all span').each(function () {
        sumPrice += parseFloat($(this).text());
    });
    var proObjs = $.parseJSON(localStorage.getItem('products'));
    var order = '';
    var cartId = [];
    for (var i = 0; i < proObjs.length; i++) {
        order += 'lstOrderDetail[' + i + '].productName=' + proObjs[i].productName + '&' +
        'lstOrderDetail[' + i + '].productID=' + proObjs[i].productId + '&' +
        'lstOrderDetail[' + i + '].supplyUserID=' + proObjs[i].supplyUserID + '&' +
        'lstOrderDetail[' + i + '].supplyID=' + proObjs[i].supplyId + '&' +
        'lstOrderDetail[' + i + '].supplyName=' + proObjs[i].supplyName + '&' +
        'lstOrderDetail[' + i + '].supplyProductID=' + proObjs[i].id + '&' +
        'lstOrderDetail[' + i + '].supplyAreaID=' + proObjs[i].supplyAreaID + '&' +
        'lstOrderDetail[' + i + '].productNum=' + $("#buyNum").val() + '&' +
        'lstOrderDetail[' + i + '].overPlusNum=' + (parseFloat(proObjs[i].overPlusNum) - parseFloat($("#buyNum").val())) + '&' +
        'lstOrderDetail[' + i + '].productPrice=' + proObjs[i].price + '&' +
        'lstOrderDetail[' + i + '].price=' + (parseFloat($("#buyNum").val()) * parseFloat(proObjs[i].price)) + '&' +
        'lstOrderDetail[' + i + '].spec=' + proObjs[i].specName + '&' +
        'lstOrderDetail[' + i + '].catchWay=' + proObjs[i].valuesName + '&' +
        'lstOrderDetail[' + i + '].weight=' + proObjs[i].svName + '&';
        cartId.push(proObjs[i].cartId);
    }
//	order.push({name:'userId',value:'86'});
//	order.push({name:'lstOrderDetail',value:JSON.stringify(products)});
    order += 'userId=' + userid +
    '&consAddr=' + $('#consAddr').text() + '&consignee=' + $('#Uname').text() + '&consMobile='
    + $('#consgneePhn').text() + '&price=' + sumPrice + '&cartId=' + cartId + '&payType=' + payType
    + "&remark=" + $("#remarks").val()+"&preRecvTime="+$("#preRecvTime").val();//return;
    commitOrderStatus = 2;
    $.ajax({
        url: server_url + "rest/buyerOrder/addOrder.do?ran="+Math.random(),
        type: 'post',
        data: order,
        error: function () {
            easyAlert(contants.systemError);
        },
        success: function (msg) {
            if(msg.retCode != '0000'){
                alert(msg.retMsg)
                commitOrderStatus = 1;
                return;
            }
            localStorage.setItem('goOrder', '1');
            window.location.href = server_url + "/buyerOrder/orders.do";
        }
});
}
//买家信息
var loadBuyerInfo = function () {
    //var userId = localStorage.getItem("userId");
    var userId = userid;

    $.ajax({
        url: server_url + "rest/buyerOrder/getBuyerInfo.do?userId=" + userId,
        type: 'get',
        data:{ran:Math.random()},
        error: function () {
            easyAlert(contants.systemError);
        },
        success: function (msg) {
            var bur = msg.data;
            if (null != bur) {
                localStorage.setItem("buyerInfo", JSON.stringify(bur));
                //console.log(bur);

                if (bur.consigneeList != null && bur.consigneeList.length > 0) {
                    var consignee = '<div onclick="editAddr(\'' + bur.consigneeList[0].id + '\')" \
								class="" consigneeId="\'' + bur.consigneeList[0].id + '\'">\
						<p>收货人：' + bur.consigneeList[0].consigneer + '\
						<span style="display: none" id="Uname">' + bur.consigneeList[0].consigneer + '</span>\
						<span style="display: none" id="consgneePhn">' + bur.consigneeList[0].mobile + '</span>\
					<span>' + bur.consigneeList[0].mobile + '</span>\
					</p>\
					<span id="consAddr">' + bur.consigneeList[0].provinceName + bur.consigneeList[0].cityName + bur.consigneeList[0].countyName + bur.consigneeList[0].consigneerAddress + '</span>\
					</div>\
					<p></p>';
                    $("#consignee").html(consignee);
                } else {
                    $("#addAddress").show();
                }
            } else {
            }
            getProduct();
        }
    });

}
//修改收货地址
var editAddr = function (consigneeId) {
    localStorage.setItem("consigneeId", consigneeId);
    window.location.href = server_url + "buyer/product/editConsigneeAddr.do?url=" + server_url + "/buyer/product/addOrder.do";
}